package amst.system;

import java.util.Date;
import java.util.Random;

import amst.BarChart;

/*Jest to system skladajacy sie z trzech kolejek i schedulera*/
public class PacketSystem {

	private SystemQueue[] queues = new SystemQueue[3];
	private Scheduler scheduler = null;
	private Random random = null;
	private double time;
	private BarChart chart = null;
	private double simulationTime;

	public PacketSystem(SystemQueue queue1, SystemQueue queue2,
			SystemQueue queue3, Scheduler scheduler0, BarChart chart) {
		queues[0] = queue1;
		queues[1] = queue2;
		queues[2] = queue3;
		scheduler = scheduler0;
		queue1.setPacketSystem(this);
		queue2.setPacketSystem(this);
		queue3.setPacketSystem(this);
		random = new Random();
		random.setSeed(new Date().getTime());
		this.chart = chart;
	}

	// pobierz wirtualny czas systemu
	public double getPSTime() {
		return time;
	}

	public void setPSTime(double stime) {
		this.time = stime;
	}

	public void setScheduler(Scheduler scheduler0) {
		this.scheduler = scheduler0;
	}

	public void setSimulationTime(double simulationTime) {
		this.simulationTime = simulationTime;
	}

	public void process() {
		int index = 0;
		double stime = 0;

		while (stime < simulationTime) {
			Packet packet = null;
			System.out.println("System time: " + stime);
			index = scheduler.findNextQueue(queues, time);

			packet = queues[index].getPacket();
			if (packet != null) {
				stime = this.getPSTime();
				stime += packet.getServiceTime();

				// System.out.println("Rozmiar kolejki(" + (index+1) + "): " +
				// queues[index].getSize());
				
				 System.out.println("Obsluguje pakiet z kolejki(" + (index+1) +
				 "): " + packet.getServiceTime() + " systime: " + time +
				 " counter: " + queues[index].getCounter() + " Dlugosc kolejek: " +
				 queues[0].getSize() + " " + queues[1].getSize() + " " +
				 queues[2].getSize());
				 
				// for (int i = 0; i < queues.length; i++) {
				// System.out.println("Srednie opoznienie: kolejka(" + (i+1) +
				// ")->" + queues[i].getMeanPacketDelay());
				// }
				for(int ii=0; ii<3; ii++) {
					chart.setValuePoint(queues[ii].getMeanPacketDelay(), "Q" + (ii+1), "Delay");
					System.out.println("Delay " + ii + ": " + queues[ii].getMeanPacketDelay());
				}
				
				try {
					Thread.sleep((int) packet.getServiceTime() + 1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				this.setPSTime(Math.max(stime, this.getPSTime()));
			}
		}
	}

}
